<template>
  <div class="app-container-flex">
    <full-screen
      v-model="showDialog"
      :title="title"
      :btnList="fullInfo.btnList"
    >
      <!-- 主表信息 -->
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-supplierName>
              <el-input
                class="not-mongolia"
                type="input"
                placeholder="请选择供应商"
                :disabled="true"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="selectSupplier"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-depotName>
              <el-input
                class="not-br not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="openDepotWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-time>
              <el-date-picker
                @change="timeChange"
                v-model="formInfo.data.time"
                :clearable="true"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                style="width: 400px"
                :shortcuts="$fn.pickerOptionsFn()"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[
                  new Date(2000, 1, 1, 0, 0, 0),
                  new Date(2000, 1, 1, 23, 59, 59),
                ]"
              ></el-date-picker>
            </template>
          </page-form>
        </div>
      </div>
      <!-- 明细信息 -->
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          />
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tabIndex="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                @handleEvent="handleEvent"
                :mergeData="tableInfo.mergeData"
                :mergeFiled="tableInfo.mergeFiled"
                :summaryFieldList="tableInfo.summaryFieldList"
                :isDynamic="true"
              >
                <template v-slot:col-licenseNumber="scope">
                  <p>{{ scope.row.licenseNumber || '-' }}</p>
                  <p>{{ scope.row.brandName || '-' }}</p>
                </template>
                <template v-slot:col-commonName="scope">
                  <p>{{ scope.row.commonName || '-' }}</p>
                  <p>{{ scope.row.productCode || '-' }}</p>
                  <p>{{ scope.row.alias || '-' }}</p>
                </template>
                <template v-slot:col-type="scope">
                  <p>{{ scope.row.productTypeValue || '-' }}</p>
                  <p>{{ scope.row.codeTypeValue || '-' }}</p>
                  <p>{{ scope.row.productCategoryValue || '-' }}</p>
                </template>
                <template v-slot:col-standard="scope">
                  <p>{{ scope.row.standard || '-' }}</p>
                  <p>{{ scope.row.unitName || '-' }}</p>
                </template>
              </page-table>
            </el-form>

            <!-- 仓库选择框 -->
            <select-depot
              v-if="selectDepotInfo.visible"
              v-model:showDialog="selectDepotInfo.visible"
              :checkBox="false"
              :highlightRow="true"
              @callback="selectDepotCallBack"
            />
            <select-supplier
              v-if="selectSupplierInfo.visible"
              v-model:show-dialog="selectSupplierInfo.visible"
              :check-box="false"
              :highlightRow="true"
              :query="selectSupplierInfo.query"
              @callback="selectSupplierCallback"
            />
            <select-surgery-product
              v-if="productInfo.visible"
              v-model:show-dialog="productInfo.visible"
              :tableData="tableInfo.data"
              :query="productInfo.query"
              @callback="selectProductCallback"
            >
            </select-surgery-product>
            <individual-modify
              :info="individualInfo"
              v-if="showIndividualDetails"
              v-model:show-dialog="showIndividualDetails"
              :query="paramsIndividual"
              @callback="individualCallback"
            ></individual-modify>
          </div>
        </div>
      </div>
    </full-screen>
  </div>
</template>

<script setup name="SurgeryAndTableReceiptModify">
import FullScreen from '@/components/FullScreen/index'
import PageForm from '@/components/PageForm/index'
import PageFilter from '@/components/PageFilter/index'
import PageTable from '@/components/PageTable/index'
import SelectDepot from '@/components/SelectDepot/index'
import IndividualModify from './IndividualModify'
import {
  withTableReceivingOrderAdd,
  withTableReceivingOrderUpdate,
  withTableReceivingOrderDetail,
  withTableReceivingOrderDetailAll,
} from '@/api/stock'
import SelectSurgeryProduct from '@/components/SelectSurgeryProduct/index'
import SelectSupplier from '@/components/SelectSupplier/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps(['visible', 'title', 'id'])

const selectSupplierInfo = reactive({
  visible: false,
  query: {
    searchType: 'org',
    searchField: 'supplierId',
    supplierAuth: 'supplierId',
  },
})

//full组件信息
const fullInfo = reactive({
  visible: false,
  btnList: [{ label: '保存', event: save, show: true }],
})
const formInfo = reactive({
  ref: null,
  data: {
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : '',
    supplierName: '',
    supplierId: '',
    time: null,
  },
  fieldList: [
    { label: '供应商', value: 'supplierName', type: 'slot' },
    { label: '仓库', value: 'depotName', type: 'slot' },
    {
      value: 'time',
      label: '选择消耗时间',
      className: 'not-br',
      type: 'slot',
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择入库仓库', trigger: 'change' },
    ],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
    time: [
      {
        type: 'array',
        required: true,
        message: '请选择消耗时间',
        trigger: 'change',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    // sort: "create_time desc"
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct, show: true },
    { type: 'button', label: '删除产品', event: removeProduct },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'totalPrice', formatter: proxy.$fn.TripartiteMethod },
  ],
  mergeData: {},
  fieldList: [
    {
      label: '通用名称\n编码\n别名',
      value: 'commonName',
      type: 'slot',
      width: 220,
    },
    {
      label: '规格\n计量单位',
      value: 'standard',
      type: 'slot',
    },
    // {
    //   label: "消耗数量",
    //   value: "consumeQty",
    //   type: "column",
    //   formatter: proxy.$fn.qtyFormatter
    // },
    {
      label: '消耗单价',
      value: 'consumePrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '产品类型\n条码类型\n产品分类',
      value: 'type',
      type: 'slot',
      width: 150,
    },
    {
      label: '收货数量',
      value: 'qty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '结算单价',
      value: 'price',
      type: 'money',
      rules: { validator: proxy.$validate.positiveMoneyZero, trigger: 'blur' },
    },
    {
      label: '金额',
      value: 'totalPrice',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '证号\n生产厂家',
      value: 'licenseNumber',
      type: 'slot',
      width: 220,
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '300',
    btList: [
      { label: '选择个体', event: selectIndividual, show: true },
      { label: '删除产品', event: removeProduct, show: true },
    ],
  },
})
const selectDepotInfo = reactive({
  visible: false,
})
let productInfo = reactive({
  visible: false,
  query: {},
})
const formRefs = ref([])
const paramsIndividual = ref({})
const showIndividualDetails = ref(false)
const individualInfo = ref({})
const index = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => tableInfo.data,
  () => {
    tableInfo.mergeData = proxy.$fn.getMergeData(val)
    tableInfo.data.forEach(
      (row) => (row.totalPrice = (row.qty || 0) * (row.price || 0))
    )
  },
  {
    deep: true,
  }
)
onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.ref]
  if (props.id) {
    filterInfo.query.receivingId = props.id
    getMain()
  }
})

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function openDepotWindow() {
  selectDepotInfo.visible = true
}
function selectDepotCallBack(row) {
  if (row) {
    formInfo.data['depotName'] = row.name
    formInfo.data.depotId = row.id
  }
}
//保存
function save() {
  const data = formInfo.data
  if (!tableInfo.data.length) {
    proxy.$message({
      message: '请选择产品',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  // let arr = tableInfo.data.filter((item)=>item.price > item.consumePrice)
  // if(arr.length) {
  //   let nameStr = arr.map(item => item.commonName).toString()
  //   proxy.$message({
  //     message: `产品【${nameStr}】结算单价不可高于消耗单价！`,
  //     type: "warning",
  //     duration: 3500,
  //     showClose: true
  //   });
  //   return;
  // }
  const { consumeTimeGreater, consumeTimeLess } = filterInfo.query
  data.consumeTimeGreater = consumeTimeGreater
  data.consumeTimeLess = consumeTimeLess
  const details = tableInfo.data
  proxy.$fn.checkForm(formRefs.value).then(() => {
    data.details = details
    const api = data.id
      ? withTableReceivingOrderUpdate
      : withTableReceivingOrderAdd
    api(data).then((resp) => {
      if (resp && resp.success) {
        showDialog.value = false
        emit('returnModify')
      }
    })
  })
}
function timeChange(val) {
  if (val && val.length) {
    if (
      filterInfo.query.consumeTimeGreater !== val[0] ||
      filterInfo.query.consumeTimeLess !== val[1]
    ) {
      filterInfo.query.consumeTimeGreater = val[0]
      filterInfo.query.consumeTimeLess = val[1]
      tableInfo.data = []
    }
  } else {
    filterInfo.query.consumeTimeGreater = ''
    filterInfo.query.consumeTimeLess = ''
    tableInfo.data = []
  }
}
function selectSupplier() {
  selectSupplierInfo.visible = true
}
function selectSupplierCallback(data) {
  if (formInfo.data.supplierId !== data.supplierId) {
    formInfo.data.supplierId = data.supplierId
    formInfo.data.supplierName = data.supplierName
    tableInfo.data = []
  }
}
function addProduct() {
  const { supplierId } = formInfo.data
  const { consumeTimeGreater, consumeTimeLess } = filterInfo.query
  if (!supplierId) {
    proxy
      .$confirm('请选择供应商', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        selectSupplier()
      })
    return
  }
  if (!consumeTimeGreater) {
    proxy.$message({
      message: '请选择消耗时间',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  productInfo = {
    visible: true,
    query: {
      supplierId,
      consumeTimeGreater,
      consumeTimeLess,
    },
  }
}
function selectProductCallback(data) {
  tableInfo.data = [...data, ...tableInfo.data]
}
function individualCallback(data) {
  if (data) {
    tableInfo.data[index.value] = {
      ...tableInfo.data[index.value],
      qty: data.qty,
      details: [...data.details],
      // sumPrice: data.sumPrice
    }
  }
}
function selectIndividual(row, index) {
  individualInfo.value = { ...row }
  const { supplierId } = formInfo.data
  const { consumeTimeGreater, consumeTimeLess } = filterInfo.query
  paramsIndividual.value = {
    supplierId,
    consumeTimeGreater,
    consumeTimeLess,
    price: row.price,
    receivingId: props.id || null,
    consumePrice: row.consumePrice,
    productId: row.productId,
  }
  showIndividualDetails.value = true
  index.value = index
}
function removeProduct(row = undefined) {
  if (row && row.productId) {
    tableInfo.data = tableInfo.data.filter((item) => item !== row)
  } else {
    if (tableInfo.selections.length > 0) {
      tableInfo.data = tableInfo.data.filter(
        (row) => !tableInfo.selections.includes(row)
      )
    } else {
      proxy.$message({
        message: '请选择一条操作数据',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
  }
}
function getMain() {
  withTableReceivingOrderDetail(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data
      formInfo.data.time = [
        resp.data.consumeTimeGreater,
        resp.data.consumeTimeLess,
      ]
      filterInfo.query.consumeTimeGreater = resp.data.consumeTimeGreater
      filterInfo.query.consumeTimeLess = resp.data.consumeTimeLess
    }
  })
  withTableReceivingOrderDetailAll(filterInfo.query).then((res) => {
    if (res) {
      const data = res.data.map((item) => {
        return {
          ...item,
          differenceByIdAddPrice: `${item.productId}A${item.consumePrice}`,
        }
      })
      tableInfo.data = data
    }
  })
}
</script>

<style scoped></style>
